package com.qiche.controller.mini;

import com.github.pagehelper.PageInfo;
import com.qiche.aspect.PageResult;
import com.qiche.aspect.Result;
import com.qiche.dto.SimpleInsurancePolicyItemDto;
import com.qiche.enums.ResultEnum;
import com.qiche.exception.MySystemException;
import com.qiche.model.InsurancePolicy;
import com.qiche.model.User;
import com.qiche.requestpram.PolicyListURL;
import com.qiche.service.InsurancePolicyService;
import com.qiche.util.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * 微信小程序端保单管理控制器
 * @Author: Linzewen
 * @Date: 2018/5/7 0007 16:07
 */
@Api(value = "/policys/mini",description = "【微信小程序端】保单管理控制器")
@RestController
@RequestMapping(value = "policys/mini")
public class InsurancePolicyMiniController {

    @Resource
    private InsurancePolicyService policyService;

    @ApiOperation(value ="根据条件获取保单列表" )
    @PostMapping("/list")
    public PageResult getAllPolicys(@RequestBody PolicyListURL policyListURL) {

        User currentUser = UserUtils.getCurrentUser();
        if (currentUser == null) {
            return new PageResult(ResultEnum.MEMBER_LOGIN_PAST);
        }
        policyListURL.setMerchantId(currentUser.getMerchantId());
        PageInfo<SimpleInsurancePolicyItemDto> pageInfo = policyService.selectByPolicyListURL(policyListURL);
        PageResult<List<SimpleInsurancePolicyItemDto>> listPageResult = new PageResult<>(ResultEnum.SUCCESS, pageInfo.getList());
        BeanUtils.copyProperties(pageInfo, listPageResult);
        return listPageResult;
    }

    @ApiOperation(value ="添加保单" )
    @PostMapping
    public Result add(@RequestBody @Validated InsurancePolicy policy, BindingResult result) {

        if (result.hasErrors()) {
            return Result.createByResultEnum(ResultEnum.PARAM_ERROR);
        }
        User currentUser =UserUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.createByResultEnum(ResultEnum.MEMBER_LOGIN_PAST);
        }
        try {
            return policyService.savePolicy(policy, currentUser);
        } catch (MySystemException e) {
            e.printStackTrace();
            return Result.createByResultEnum(ResultEnum.POLICY_HAS_EXISTED);
        } catch (Exception e) {
            return Result.createByResultEnum(ResultEnum.FAILURE);
        }
    }

}
